<?php

namespace app\middleware;

use app\libs\exception\ParameterException;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class AdminApiAuth implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        $controllerArr = explode('\\', $request->controller);
        $controller = end($controllerArr);
        // 不需要中间件的控制器
        $exceptControllers = ['AuthController', 'CommonController'];
        if (in_array($controller, $exceptControllers)) {
            return $handler($request);
        }

        $token = $request->header('token');
        if (!$token) {
            throw new ParameterException([
                'code' => 401,
                'msg' => 'token 不能为空！'
            ]);
        }
        $jwt_data = \app\common\service\AuthToken::verify($token);
        if (is_array($jwt_data) && isset($jwt_data['msg'])) {
            throw new ParameterException([
                'code' => 401,
                'msg' => $jwt_data['msg'],
            ]);
        }
        if (!$jwt_data || !$jwt_data->admin_id) {
            throw new ParameterException([
                'code' => 401,
                'msg' => '登录状态已过期！',
            ]);
        }
        $admin = cache('auth_admin_id-' . $jwt_data->admin_id);
        if (!$admin) {
            throw new ParameterException([
                'code' => 401,
                'msg' => 'token值已过期，请重新登录！'
            ]);
        }

        return $handler($request);
    }
}
